package cn.sibu.tuchapplication;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.TouchDelegate;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.Toast;

/**
 * Created by 刘红亮 on 15-12-23 下午1:23.
 */
public class TouchDelegateLayout extends FrameLayout{

    public TouchDelegateLayout(Context context) {
        super(context);
        init(context);
    }

    public TouchDelegateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TouchDelegateLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private CheckBox mButton;
    private void init(final Context context){
        //创建一个很小的子视图,我们要将触摸事件转发给它
        mButton = new CheckBox(context);
        mButton.setText("Tap Anywhere");
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        addView(mButton,lp);
        mButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    Toast.makeText(context,"touch",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    /**
     * TouchDelegate会将该视图(父视图)的某个特定矩形区域作为代理区域,将所有触摸事件转发给
     * checkBox(子视图).这里,矩形区域即为父视图的全部大小
     *
     * 这个过程必须在视图确定了大小以后进行,这样才能知道矩形应该有多大,
     * 所以我们选择在onSizeChanged()中添加代理区域
     * */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        if(w!=oldw || h != oldh){
            //将该视图的整个区域作为代理区域
            Rect bounds = new Rect(0,0,w,h);
            TouchDelegate delegate = new TouchDelegate(bounds,mButton);
            setTouchDelegate(delegate);
        }
    }
}
